﻿Imports Negocio
Imports Excepciones
Imports Servicios
'TODO: Patron Template Method -> Clase Abstracta
Public Class Base
    Public Modulo As Modulo = Nothing
    Protected FormValid As Boolean = True

    Sub New()

        InitializeComponent()

        Me.AutoValidate = Windows.Forms.AutoValidate.EnableAllowFocusChange
        Me.StartPosition = FormStartPosition.CenterScreen

    End Sub
    'Metodo Plantilla
    Protected Sub Base_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        PreLoad()
        Modulo = New Modulo(Me.Tag)
        Utilidades.Output.Print("#Form: " & Me.Name & " Modulo: " & Modulo.Codigo)
        Translate()
        Permissions()
        PostLoad()

    End Sub

    Protected Overridable Sub PreLoad()

    End Sub
    Protected Overridable Sub PostLoad()

    End Sub


#Region "Translate"
    Dim langControls As List(Of Control)

    Public Sub Translate()
        Try
            'Traduce los controles del formulario
            Dim contenedor As Contenedor = Current.Idioma.Contenedor(Me.Name)

            Dim titulo As String = contenedor.Caption

            If titulo <> "" Then
                Me.Text = titulo
            End If

            langControls = contenedor.Controles()
            For Each ctrl As Windows.Forms.Control In Me.Controls
                Try
                    If TypeOf ctrl Is IControlTranslatable Then
                        Dim c As IControlTranslatable = DirectCast(ctrl, IControlTranslatable)
                        c.Translate(langControls)
                    End If
                Catch ex As ControlNotFoundLocalizationException
                    Utilidades.Output.Print("@@" & Me.Name & ": Control " & ctrl.Name & " No Traducido")
                    Continue For
                Catch ex As ControlNotSupportedLocalizationException
                    Utilidades.Output.Print("@@" & Me.Name & ": Control " & ctrl.Name & " No Traducido")
                    GesBitacoras.Guardar(Me.Tag, "ExI003", New String() {ctrl.Name})
                    Continue For
                Catch ex As ControlFoundLocalizationException 'Control Traducido
                    Continue For
                Catch ex As Exception
                    Throw ex
                End Try
            Next

            Utilidades.Output.Print("Form " & Me.Name & " Traducido")
        Catch ex As Exception

        End Try
    End Sub

#End Region

#Region "Permisos"
    ''' <summary>
    ''' Verifica los permisos del módulo y los controles
    ''' </summary>
    ''' <remarks></remarks>
    Protected Sub Permissions()


        Try
            If Not Modulo.Codigo Is Nothing Then
                If Not Current.Usuario.Perfil.validarPermiso(Modulo, String.Empty) Then
                    My.Application.HandlerException(New AccessDeniedModuleException(Modulo.Codigo))
                    Me.Close()
                End If

                For Each ctrl As Windows.Forms.Control In Me.Controls
                    If Not ctrl.Tag Is Nothing Then
                        If Not Current.Usuario.Perfil.validarPermiso(Modulo, ctrl.Tag.ToString) Then
                            ctrl.Enabled = False
                        End If
                    End If
                Next
            End If
        Catch ex As Exception
            Utilidades.Output.Print(Me.Name & ": Error en Permissions => " & ex.Message)
        End Try

    End Sub

    ''' <summary>
    ''' Verifica los permisos del menu
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub PermisosMenuStrip()

        For Each ctrl As Windows.Forms.Control In Me.Controls
            If TypeOf ctrl Is MenuStrip Then
                Dim ms As MenuStrip = DirectCast(ctrl, MenuStrip)
                For Each modu As Modulo In Current.Usuario.Perfil.Modulos
                    Dim it As ToolStripItem() = ms.Items.Find(modu.Codigo, True)
                    If it.Length > 0 Then
                        If Not Current.Usuario.Perfil.validarPermiso(modu, String.Empty) Then
                            it(0).Enabled = False
                        End If
                    End If
                Next
            End If
        Next
    End Sub
#End Region

#Region "Error UI"
    Public Sub SetErrorUI(c As Windows.Forms.Control, ex As CustomException)

        Dim msg As String = Nothing
        Dim err As Mensaje = GesIdiomas.TraduceMensaje(ex.Code)
        If Not err Is Nothing Then
            msg = err.Caption
        End If

        If String.IsNullOrEmpty(msg) Then
            msg = ex.Message
        End If
        Utilidades.Output.Print("@" & Me.Name & " => Control: " & c.Name & " => Validation: " & msg)
        ErrorProviderInput.SetError(c, msg)
        FormValid = False
    End Sub

    Public Sub ResetErrorUI(c As Windows.Forms.Control)
        ErrorProviderInput.SetError(c, Nothing)
    End Sub
    ''' <summary>
    ''' Ejecuta la validacion de todos los controles del form
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Overridable Function ValidateForm() As Boolean
        FormValid = True
        Me.ValidateChildren()
        Return FormValid
    End Function

    'Function ValidateCustomControls() As Boolean
    '    Dim r As Boolean = True
    '    Dim controles As New List(Of System.Windows.Forms.Control)
    '    For Each ctrl As System.Windows.Forms.Control In FindControlRecursive(controles, Me, GetType(IControlValidatable))
    '        Try
    '            ResetErrorUI(ctrl)
    '            DirectCast(ctrl, IControlValidatable).ValidateInput()
    '        Catch ex As CustomException
    '            SetErrorUI(ctrl, ex)
    '            r = False
    '        Catch ex As Exception
    '        End Try
    '    Next
    '    Return r
    'End Function

    'Private Function FindControlRecursive(ByVal list As List(Of System.Windows.Forms.Control), ByVal parent As System.Windows.Forms.Control, ByVal ctrlType As Type) As List(Of System.Windows.Forms.Control)
    '    If parent Is Nothing Then Return list
    '    If TypeOf parent Is IControlValidatable Then
    '        list.Add(parent)
    '    End If
    '    For Each child As System.Windows.Forms.Control In parent.Controls
    '        FindControlRecursive(list, child, ctrlType)
    '    Next
    '    Return list
    'End Function
#End Region




End Class